﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using Microsoft.SharePoint.Client;

namespace BookCompanion.SilverlightCOMClient
{
  public partial class MainPage : UserControl
  {
    public class City
    {
      public String Name { get; set; }
      public String Region { get; set; }
      public String Latitude { get; set; }
      public String Longitude { get; set; }
    }
    
    public MainPage()
    {
      InitializeComponent();
      this.LoadGrid();
    }

    private void LoadGrid()
    {
      var context = ClientContext.Current;
      Web web = context.Web;
      ListCollection lists = web.Lists;
      List list = lists.GetByTitle("Citta");
      ListItemCollection listItems = list.GetItems(CamlQuery.CreateAllItemsQuery());
      context.Load(listItems);
      context.ExecuteQueryAsync(
        (o,a) =>
        {
          var cities = new List<City>();
          foreach (var listItem in listItems)
          {
            cities.Add(new City
            {
              Name = listItem["Title"].ToString(),
              Region = listItem["Regione"].ToString(),
              Latitude = listItem["Latitudine"].ToString(),
              Longitude = listItem["Longitudine"].ToString()
            });
          }
          this.Dispatcher.BeginInvoke(() => dgCities.ItemsSource = cities);
        },
        (o,a) => { }
        );        
    }
  }
}
